nuysoft / Mock

A simulation data generator
http://mockjs.com
Other
19.53k stars 2.66k forks source link

解决mock请求回调函数为异步或Promise时正常返回数据 #442

Open massive688 opened 3 years ago

massive688 commented 3 years ago

修改https://github.com/nuysoft/Mock/blob/refactoring/src/mock/xhr/xhr.js 291-300行

                that.custom.options.headers = that.custom.requestHeaders
            let promise = convert(that.custom.template, that.custom.options)
                if (typeof promise.then === 'function') {
                    promise.then(resp=>{
                        // fix #92 #93 by @qddegtya
                        that.response = that.responseText = JSON.stringify(resp,null, 4)

                        that.readyState = MockXMLHttpRequest.DONE
                        that.dispatchEvent(new Event('readystatechange' /*, false, false, that*/ ))
                        that.dispatchEvent(new Event('load' /*, false, false, that*/ ));
                        that.dispatchEvent(new Event('loadend' /*, false, false, that*/ ));
                    })
                } else {
                    // fix #92 #93 by @qddegtya
                    that.response = that.responseText = JSON.stringify(promise,null, 4)

                    that.readyState = MockXMLHttpRequest.DONE
                    that.dispatchEvent(new Event('readystatechange' /*, false, false, that*/ ))
                    that.dispatchEvent(new Event('load' /*, false, false, that*/ ));
                    that.dispatchEvent(new Event('loadend' /*, false, false, that*/ ));
                }
wll8 commented 3 years ago

搞个 PR

Tmaof commented 1 year ago

解决Mock.mock()中不能使用Promise和异步函数async的问题。 Addresses an issue where Promise and the asynchronous function async cannot be used in Mock.mock(). 你可以下载: You can download:

npm i mockjs-pro

https://www.npmjs.com/package/mockjs-pro?activeTab=readme