【发布时间】:2020-05-13 23:14:26
【问题描述】:
如何使用 promise 的值将其添加到对象属性?如果有人可以帮助我,将不胜感激。
//dolar.js
const axios = require('axios');
const url ='https://s3.amazonaws.com/dolartoday/data.json';
async function getTasaDolar(priceBs) {
axios.get(url).then(function (response) {
return response.data.USD.transferencia;
}).catch(function(error) {
}).then(function(response) {{
console.log('--------');
console.log(priceBs/response);
return priceBs/response;
}});
}
module.exports = getTasaDolar;
//object.js
const getTasaDolar = require('./dolar.js');
async function myFunc ({name, brand, category, priceBs}) {
const object = {
name,
brand,
category,
priceBs,
priceDolar : getTasaDolar(priceBs)
}
return object;
}
const hola = myFunc({name:`hola`, brand: `Chocozuela`, category:`Carnes`, priceBs:645000});
console.log(hola);
当我运行它时,输出是:
Promise {
{ name: 'hola',
brand: 'Chocozuela',
category: 'Carnes',
priceBs: 645000,
priceDolar: Promise { undefined } } }
--------
3.467229680260142.
如您所见,值 3.46 是 consoled.log 但是当我 console.log hola 对象时,属性 priceDolar 是 Promise {undefined}
【问题讨论】:
-
getTasaDolar函数不返回任何东西 - 试试return axios.get(url)........- 因为它是一个异步函数,它肯定会返回一个承诺......所以你需要await getTasaDolar -
为什么要使用两个 then 块?
-
getTasaDolar也是async无缘无故 -
我尝试格式化您的代码,使其更具可读性,但那些双括号是怎么回事,即
.then(function(response) {{???? -
@Phil - 这是有效代码:p
标签: javascript object asynchronous promise response