Using a function more directly in a promise

天涯浪子 提交于 2019-12-11 12:45:13

问题


Is there a way to express this:

    imagePFFileFromUrl(exampUrl) // (returns a promise)
    .then(function(xxx))
        // that syntax gives you the results of the
        // imagePFFileFromUrl inside the variable xxx.
        // I then use it in another function which
        // returns another promise...
        {
        return saveImageFile(xxx, anotherArgument) // (returns a promise)
        })
    .then(function(savedPFFile)

more like this ..

    imagePFFileFromUrl(exampUrl)
    .then(saveImageFile(...the results from imagePFFileFromUrl ...))
    .then(function(savedPFFile)

when using promise?


回答1:


Your .then()'s need to have 1 or 2 call back functions. If there is 1, it takes in the resolved value of the promise. If there are two, the second takes the rejected value of the promise. So, no, you can't do what you are trying to do.


Here's a good example of the pattern, with two arguments, notice at return synchUsers




回答2:


You can use the function bind to achieve this. Bind creates a new function with the first parameter being the this object and any following parameters being passed to the function. When calling the new function created by bind(), any parameters are in addition to the parameters passed to bind().

imagePFFileFromUrl(exampUrl)
  .then(saveImageFile.bind(null, "name"))
  .then(function(savedPFFile)

so essentially, you are passing the return values of the first promise as the second parameter to the saveImageFile function. With the first parameter being the string value "name".



来源:https://stackoverflow.com/questions/32766623/using-a-function-more-directly-in-a-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!