0

node.js の promise に when.js を使用しています。次のような関数があります。

function my_func() {
    var d = when.defer();

    // Async actions simulated with timeout
    setTimeout(function() {
        //...
        if(error) {
            return d.resolve(error);
        }
        d.resolve(result);
    }, 1000)

    return d.promise;
}

私は次のように呼びます:

my_func().then(
    function(res) {
        //...
    },
    function(err) {
        // Handle error
    }
);

ES6 Promises で同じことを行うにはどうすればよいですか?

4

3 に答える 3

2

元の関数にはif (error)条件にいくつかの間違いがあったため、更新されたスニペットは次のとおりです。

function my_func() {
    var d = when.defer();

    // Async actions simulated with timeout
    setTimeout(function() {
        //...
        if(error) {
            d.reject(error);
        }
        d.resolve(result);
    }, 1000)

    return d.promise;
}

に変わります

function my_func() {
  return new Promise(function (resolve, reject) {
    //Async actions simulated with timeout
    setTimeout(function () {
      //...
      if (error) {
        reject(error);
      }
      resolve(result);
    }, 1000);
  });
}

これは、 MDN のドキュメントで十分にカバーされています。Promise

于 2016-04-27T14:21:49.600 に答える
1
//Creating promise
 function my_func() {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
        //...
        if(error) {
           reject(Error("Error Message"));
        }
        resolve("Success message")
    }, 1000)
    });
}
//Using it
my_func().then(function(response){
    console.log("Success!", response);
}, function(err){
    console.error("Failed!", err);
})
于 2016-04-27T14:23:35.313 に答える