【问题标题】:Is it possible to concat string array with Promise<string[]> to return Promise<String[]> in typescript/javascript?是否可以将字符串数组与 Promise<string[]> 连接以在 typescript/javascript 中返回 Promise<String[]>?
【发布时间】:2020-12-21 23:00:13
【问题描述】:
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 吗?

【问题讨论】:

  • 实际上没有什么是异步的。您可以返回一个包装您的字符串的承诺,但该字符串的处理已经发生并且承诺已经解决。
  • return [...arr1, ...(await arr2)]

标签: javascript typescript promise


【解决方案1】:

试试这个...?

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))
}

【讨论】:

    【解决方案2】:

    是的!

    只需.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))
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-16
      • 1970-01-01
      • 2021-08-11
      • 2021-01-02
      • 1970-01-01
      • 2019-04-24
      • 2017-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多