简体   繁体   中英

Nesting promises with q-io

I'm trying to make sense of the idea that promises that return another promise become the value of the return. That's what I read in the Q docs on the wiki. https://github.com/kriskowal/q#tutorial

Its the ideal situation, as I'm using q-io/http which uses a promise to make the request. However, the function returns the value of the body in a new promise.

Rather than nesting the rest of my code inside my first function. I want to be notified when the nested promise is complete. However, because of scope, I can't seem to do it. But I keep reading that my outer function should become the value of the inner promise. Am I missing something?

Ex.

module.exports = function (obj) {
  var getFiles = HTTP.request(obj);

  getFiles
   .then(function(res) {
      return res.body.read()
    });
  return getFiles;
};

I want to be notified when res.body.read() fulfills its promise using Q.all(), but I don't know how to get that value. I feel like getFiles should become that inner promise. Right?

I feel like getFiles should become that inner promise. Right?

No. A promise won't change it's value. However, the .then method does return a new promise that will be resolved with the result of the "inner promise" read method (which will be called when getFiles is resolved).

You can shorten your code to

module.exports = function (obj) {
  return HTTP.request(obj).then(function(res) {
    return res.body.read()
  });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM