Redux-来自web套接字请求的异步响应



我实现了一个websocket接口,这样我就可以用来发送请求。问题是响应是异步的,它最初返回的是空数组,因为retObj不是从我发送的回调函数中更新的。我如何使这个函数在更新后返回填充的数组。我的服务是这样的:

import * as interface from '../webSocket'
const carService = () => {
return {
getCars: () => {
interface.sendRequest(function (returnObject) {
//
}).then(d => d)
}
}
}
export default carService()

这就是我的行为:

import { GET_CARS } from '../constants'
import carService from '../carService'
export const getCars = () => async (dispatch) => {
try {
const cars = await carService.getCars()
console.log("At cars actions: ", cars) // logs: Array []
dispatch(getCarsSuccess(cars))
} catch (err) {
console.log('Error: ', err)
}
}
const getCarsSuccess = (cars) => ({
type: GET_CARS,
payload: cars
})

您只需将回调包装成promise,因为它一开始就不是promise,这就是为什么您不能使用thenawait

import * as interface from '../webSocket'
const carService = () => {
return {
getCars: () => {
return new Promise(resolve => interface.sendRequest(function (returnObject) {
resolve(returnObject.msg)
}));
}
}
}
export default carService()

问题是,除非函数返回Promise,否则不能await。所以,正如你所猜测的,问题在于carService.getCars的定义。试试这个:

getCars: () => {
return new Promise((resolve, reject) => {
interface.sendRequest(function(returnObject) {
// if theres an error, reject(error)
resolve(returnObject);
})
})
}

或者,如果sendRequest是async函数,只需返回sendRequest:的返回值

getCars: () => {
return interface.sendRequest()
}

最新更新