Creating a (ES6) promise without starting to resolve it

后端 未结 6 522
甜味超标
甜味超标 2020-12-07 17:15

Using ES6 promises, how do I create a promise without defining the logic for resolving it? Here\'s a basic example (some TypeScript):



        
6条回答
  •  天涯浪人
    2020-12-07 17:50

    Good question!

    The resolver passed to the promise constructor intentionally runs synchronous in order to support this use case:

    var deferreds = [];
    var p = new Promise(function(resolve, reject){
        deferreds.push({resolve: resolve, reject: reject});
    });
    

    Then, at some later point in time:

     deferreds[0].resolve("Hello"); // resolve the promise with "Hello"
    

    The reason the promise constructor is given is that:

    • Typically (but not always) resolution logic is bound to the creation.
    • The promise constructor is throw safe and converts exceptions to rejections.

    Sometimes it doesn't fit and for that it the resolver runs synchronously. Here is related reading on the topic.

提交回复
热议问题