是否可以将字符串数组与 Promise<string[]> 连接以在 typescript/javascript 中返回 Promise<String[]>?


public async getPromiseArray(from: number, to: number): Promise<String[]> {
const someArray = this.someArray;
const arr1 = someArray.slice(from, from + 2); // This returns an array of string
const arr2 = this.storageService.get(from + 3, to) // This returns Promise<String[]>
// Is is possible to return a promise<String[]> which is a concat of arr1 and arr2
}

我可以等待arr2并返回字符串数组,但是否可以直接返回Promise<字符串[]>从这个方法?

试试这个。。。

public async getPromiseArray(from: number, to: number): Promise<String[]> {
try {
const someArray = this.someArray;
const arr1 = someArray.slice(from, from + 2);
const arr2 = await this.storageService.get(from + 3, to);
resolve(arr1.concat(arr2))
}
reject(arr1.concat(arr2))
}

确实如此!

只需.then您的承诺,然后连接到那里:

//If you return a promise and don't use `await`, then there's no need for `async`
public getPromiseArray(from: number, to: number): Promise<String[]> {
const someArray = this.someArray;
const arr1 = someArray.slice(from, from + 2); // This returns an array of string
const arr2 = this.storageService.get(from + 3, to) // This returns Promise<String[]>
// Is is possible to return a promise<String[]> which is a concat of arr1 and arr2
return arr2.then(arr2 => arr1.concat(arr2))
}

最新更新