gpt4 book ai didi

javascript - 在 promise 解决后解决值(value)

转载 作者:行者123 更新时间:2023-11-29 16:57:12 24 4
gpt4 key购买 nike

我有一个这样的代码..我想获取一些内容并在所有内容加载后做一些事情。所以我使用 Promise.all 并稍后访问已解析的值。但它正在提供值(value),但喜欢 Promise {'content here'}。 (请参阅 console.log..)我打算使用 Regex 来提取它,但后来我检查了它的类型,它不是字符串而是没有键的对象?为什么?

      var request=require('request');

var urls=['someurl','someurl2','someurl3'];
var contents=[];

urls.forEach(function (u) {
contents.push(getContent(u) );
});

Promise.all(contents)
.then(function () {
// All should be loaded by now?

// Promises which are resolved are fulfiled, and values can be accessed later right?
contents.forEach(function (promise) {
var content = Promise.resolve(promise);
console.log(content); // Promise {'test'} ??
console.log(typeof content,Object.keys(content));
// object [] ???
});

}).
catch(function(err) {
//handle error here

});



function getContent(url) {
return new Promise ( function (resolve,reject) {
/** commented and stripped out for testing
request(url, function (err,response, data) {
if(err) {
reject(Error(err));
}

}); **/
resolve("test");
});
}

最佳答案

contents 仍然只是 promise 。
您永远无法直接提取 promise 的值(value);您只能从 then() 回调中使用它。

相反,Promise.all() 为结果数组返回一个 promise

更改您的 then() 调用以将该数组作为回调参数并直接使用它。

关于javascript - 在 promise 解决后解决值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31389600/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com