Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

javascript - How to structure nested Promises

I have a situation where I think the only choice for me is to nest some Promises within each other. I have a Promise that needs to be performed and a method that does something until that Promise is complete. Something like this:

let promise = new Promise((resolve, reject) => {

  // Do some stuff

});

doSomethingUntilPromiseisDone(promise);

However, within my Promise, I need to execute another method that returns another Promise:

let promise = new Promise((resolve, reject) => {

  fetchValue(url)
    .then((value) => {

      // Do something here

    }).catch((err) => {
      console.error(err);
    });

});

doSomethingUntilPromiseisDone(promise);

But now, in the fetchValue method's then statement, I have another method I need to execute that, guess what, returns another Promise:

let promise = new Promise((resolve, reject) => {

  fetchValue(url)
    .then((value) => {

      saveToCache(value)
        .then((success) => {

          console.log('success!!');
          resolve('success');

        });

    }).catch((err) => {
      console.error(err);
    });

});

doSomethingUntilPromiseisDone(promise);

So in the end, I have a Promise, within a Promise, within a Promise. Is there someway I can structure this better so that it is more straightforward? It seems like nesting them within each other is counter to Promise's intended chaining approach.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use .then()

let doStuff = (resolve, reject) => {/* resolve() or reject() */};
let promise = new Promise(doStuff);
doSomethingUntilPromiseisDone(
  promise 
  .then(value => fetchValue(url))
  .then(value => value.blob())
  .then(saveToCache)
)
.then(success => console.log("success!!"))
.catch(err => console.error(err))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...