【问题标题】:resolving values after promise has resolved在 promise 解决后解析值
【发布时间】:2015-07-14 04:08:18
【问题描述】:

我有这样的代码.. 我想获取一些内容,然后在加载之后,做点什么。 所以我使用 Promise.all 并稍后访问解析的值。但它给出了价值,但就像 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");
       });
       }

【问题讨论】:

    标签: javascript promise es6-promise


    【解决方案1】:

    contents 仍然只持有承诺。
    你永远不能直接提取承诺的价值;您只能从 then() 回调中使用它。

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

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

    【讨论】:

      【解决方案2】:

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

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

      第二件事:你没有正确地创建一个 Promise,本质上,你永远不会在你的 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 会得到解决,并且您提供的输入会被传递。 当您在Promise.all() 中指定的所有承诺都解决后,回调将被执行,您将能够访问resolve() 返回的数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-05
        • 2017-10-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多