在promise解决后解析值

resolving values after promise has resolved

本文关键字:promise 解决      更新时间:2023-09-26

我有一个像这样的代码。我想要获取一些内容,并在加载完毕后做一些事情。所以我用Promise。稍后再访问所有解析值。但它给出了值,但像Promise {' content here'}。(见console.log . .)我要用正则表达式来提取它,然后我检查它的类型不是字符串,而是没有键的对象?为什么?

      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仍然只持有承诺。
你永远不能直接提取承诺的价值;您只能从then()回调中使用它。

相反,Promise.all()返回一个承诺数组的结果

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

首先,您以错误的方式访问结果:

Promise.all(contents).then( function(data) {
    // data holds an array with the return values of the promises
    console.log(data);
});

第二件事:你没有正确地创建一个承诺,本质上,你从来没有解决他们在你的getContent()函数,所以你永远不会得到你想要的数据!

function getContent(url) {
       return new Promise ( function (resolve,reject) {
        request(url, function (err,response, data) {
         if(err) {
            // reject the promise in case of error
            reject(Error(err));
         } else {
            // resolve the promise with the output you need
            resolve(data);
         }
});

当你调用resolve()时,承诺被解决,你给它的输入被传递。当您在Promise.all()中指定的所有承诺都被解析后,回调将被执行,您将能够访问resolve()返回的数据。