上下文:
我需要调用一个函数(函数A)来发出两次HTTP请求,之后,我需要调用另一个函数(函数B)来计算两个数组
正常的顺序应该是
- (函数 A 和函数 A)异步
- 当另外 2 个完成后,功能 B
所以我答应了,但问题是,我不知道如何正确地编写它的语法,我使用 Coffeescript。
这是我到目前为止所得到的,但现在它不起作用
myCoolPromise = () ->
return new Promise (resolve, reject) ->
postRequest(diagUrl, diagnosisBody, storesConnectionObject)
postRequest(storesUrl, brandBody, storesObject)
success = true
if success
resolve 'stuff worked'
else
reject Error 'it broke'
myCoolPromise(storesObject.storesArray, storesConnectionObject.storesArray, absentObject).then (response) ->
console.log 'success', response
handleResult(storesObject.storesArray, storesConnectionObject.storesArray, absentObject)
.catch (error) ->
console.error 'failed', error
最佳答案
我回答我自己的问题以在 StackOverflow 中保留踪迹
我的问题是语法方面
我更改了 postRequest
以返回一个 promise ,如果请求以状态码 200 返回则解析,如果错误则拒绝,并将这两个函数链接在一个 promise 中,如下所示:
myCoolPromise = (diagUrl, diagnosisBody, storesUrl, brandBody) ->
return new Promise (resolve, reject) ->
postRequest(diagUrl, diagnosisBody)
.then (storesConnectionObject) ->
postRequest(storesUrl, brandBody)
.then (storesObject) ->
resolve handleResult(storesObject, storesConnectionObject)
.catch (error1) ->
reject error1
.catch (error2) ->
reject error2
我仍然愿意寻求更好的方法来解决这个问题,谢谢
关于javascript - 在 CoffeeScript 中使用两个异步函数进行 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44647060/