等待订阅无法正常工作

时间:2018-08-15 17:06:08

标签: typescript async-await

在我的应用程序中单击一个按钮时。在继续进行下一步功能之前,我需要将某些项目上传到API。

我已经尝试了很多方法来等待代码运行,但是似乎无法正常工作,只能继续前进。

这是我的代码示例:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    if let pickedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
        self.userProfileImage.contentMode = .scaleAspectFit
        self.userProfileImage.image = pickedImage
    }

    picker.dismiss(animated: true, completion: nil)
}

因此,方法AssignEmailAttachments实际上需要在继续之前等待响应。

有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:0)

subscribeToContainer看起来不正确,这里您需要将基于异步回调的API(假定它是RxJs Observable)转换为Promise。大多数此类情况可以通过Promise构造函数完成:

subscribeToContainerItem(item: any) {
    // immediately return promise instance
    return new Promise((resolve, reject) => {
        // call inner API and wait for async response
        this._azureStorageService.getContainerItemByContainerIdItemName(this._routeIdService.getStorageContainerId(), item.Name)
            .subscribe(
                // in callback call resolve function to resolve the promise
                res => resolve({ filename: item.Name, path: res.url }), 
                // in case of error reject result promise
                err => reject(err)
            );
    });
}

对于附件,您需要等待所有附件被填充。我使函数简短了一点:

assignEmailAttachments() {
    // map each element to async operation which resolves with populated item
    const populatedAttachmentPromises = this.selectedAttachments.map(item => this.subscribeToContainerItem(item));
    // wraps them with promise, which be resolved when all items are populated
    return Promise.all(populatedAttachmentPromises);
}

然后在onClick处理程序中,您还需要等待promise解析,然后再继续操作:

onSendEmailClick(): void {
    if (this.selectedEmail.Content) {
        this.assignEmailContent()
            .then(attachments => this.fireAfterCompleted(attachments));
    }
}